<?php
class  PublicAction extends Action{
    public function _initialize(){
	   header("content-type:text/html;charset=utf-8");
	  //check_do_per();
	  if(empty($_SESSION["admin"]))$this->redirect("Login/index");  
	}
    public function left(){
	   $parid=$_GET["parid"]?$_GET["parid"]:0;
	   $syscolumn=syscolumn($parid);
	   $this->assign("syscolumn",$syscolumn);
	   $websetup=M("websetup");
	   $webname=$websetup->getField("webname");
	   $this->assign("webname",$webname);
	   $this->display();
	}
	public function top(){
	   $websetup=M("websetup");
	   $weburl=$websetup->limit(1)->getField("weburl");
	   $this->assign("weburl",$weburl);
	   $this->display();   
	   
	}
	public function main(){
	   set_time_limit(0);//设置程序执行时间为无限
	   
	   $this->display();   
	   
	}
	public function upload(){
	   $websetup=M("websetup");
	   $setup=$websetup->field("webname,weburl")->find();
	   $this->assign("setup",$setup);
	   $type=$_GET["type"];
	   $this->assign("type",$type);
	   $this->display();
	}
	public function doupload(){//单个文件
	   if(empty($_FILES)) $this->error("出现错误");
	   $is_thumb=$_GET["is_thumb"];//是否要生成缩略图
	   $thumb_w=$_GET["thumb_w"];//宽度
	   $thumb_h=$_GET["thumb_h"];//高度
	   $thumb_label=$_GET["thumb_label"];//标志
	   $thumb_type=$_GET["thumb_type"];
	   
	   $is_wm=$_GET["is_wm"];//是否要打水印
	   $wm_type=$_GET["wm_type"];//水印类型
	   $wm_pos=$_GET["wm_pos"];//水印位置
	   
		     Vendor("LJW.Inc_File");
			 import("ORG.Cons");
			 $myfile=new Inc_File(Cons::$sysconfig["max_pic_size"]);
		     $savepath="Public/Uploads";
			 //根据时间建立不同的文件夹,防止文件中图片过多
			 $t=date(Ymd);
			 $savepath.="/".$t;
			 if(!file_exists($savepath))$myfile->CreateDir($savepath);
			 chmod($savepath,0777);
			 if($savefile=$myfile->UploadFile($_FILES['file1'],$savepath)){
			    if(!is_file($savefile))alert($savefile);
				//是否要生成缩略图
			    if($is_thumb){
				   $size=getimagesize($savefile);$width=$size[0];$height=$size[1];//获取上传图片大小
				   if($width>$thumb_w||$height>$thumb_h||!empty($thumb_label)){
				         switch($thumb_type){
						    case "1"://普通
							  break;
						    case "2"://类淘宝
							  $w=$width/$thumb_w;$h=$height/$thumb_h;
							  if($w>$h){
							     $thumb_h=$height/$w;
							  }else{
							     $thumb_w=$width/$h;
							  }
							break;
						 }
						 $small_file=encode_spic($savefile,$thumb_label);
					     if(empty($thumb_label)){
						   //删除原文件
						   $myfile->image_resize($savefile,$thumb_w,$thumb_h,$small_file,true);
						 }else{
						   //不删除原文件
						   $myfile->image_resize($savefile,$thumb_w,$thumb_h,$small_file,false);
						 }	 
				   }
				}   
				//是否要打水印
				if($is_wm){
				     switch($wm_type){
					    case "1"://文字水印
						    $myfile->addsy($savefile,Cons::$websetup["wm_text"],$wm_pos,Cons::$websetup["wm_text_color"]);
						break;
						case "2"://图片水印
						    $myfile->watermark($savefile,$savepath."/".basename(Cons::$websetup["wm_pic"]),$wm_pos);
						break;
					 }
				}
				header("Content-type:text/html;charset=utf-8");
				echo "<script>alert('上传成功');window.close();window.returnValue='$savefile|".$_FILES['file1']['name']."';</script>";
			 }
	}
	
	
	 public function logout(){//退出登录
        foreach($_SESSION as $k=>$v){
	       unset($_SESSION[$k]);
	    }
		$this->redirect("Login/index");
	 }
	
	 public function backupdb(){//备份数据库   这个需要file权限
	        header("Content-type:text/html;charset=utf-8");
	        Vendor("LJW.sql");
			$dbbakdir="dbbak";
			if(!is_dir($dbbakdir))@mkdir($dbbakdir);
			@chmod($dbbakdir,0777);
			$dbbakdir=str_replace("\\","/",realpath($dbbakdir));
			$dbback=new sql(C("DB_HOST"),C("DB_NAME"),C("DB_USER"),C("DB_PWD"),$dbbakdir);
			$dbback->BackupDatabase();
			echo "数据备份成功";
			echo "<br>";
			echo "你可以到服务器中下载备份文件.(".$dbbakdir.")";
	 }
	 
	 public function restoredb(){//还原数据库   这个需要file权限
	        header("Content-type:text/html;charset=utf-8");
	        Vendor("LJW.sql");
			$dbbakdir="dbbak";
			$dbbakdir=str_replace("\\","/",realpath($dbbakdir));
			$dbback=new sql(C("DB_HOST"),C("DB_NAME"),C("DB_USER"),C("DB_PWD"),$dbbakdir);
			if($dbback->RestoreDatabase()){
			    alert('数据库还原成功');
			}
	 }
	 
	 public function bakdb(){//备份数据库  参考帝国备份王 不需要很特殊的权限
	 	$step=$_GET["step"]?$_GET["step"]:"step1";
	 	$this->assign("step",$step);
	 	Vendor("LJW.empirebak");
	 	$mybak=new empirebak(C("DB_HOST"),C("DB_PORT"),C("DB_USER"),C("DB_PWD"));
	 	switch($step){
	 		case "step1":	 		
	 		  $this->assign("alldb",$mybak->getAllDb());
	 		break;
	 		case "step2":
	 		  $db=$_GET["db"];
	          $this->assign("alltables",$mybak->getAllTable($db));
			  $this->assign("savepath",$db."_".date("YmdHis"));
	 		break;
			case "step3":
			
			
			break;
	 	}
	 	$this->display();
	 }
	 public function redb(){//还原数据库
	 	
	 	
	 }
	 
	 public function showupload(){//上传图片管理
	    ob_start();
		echo "<link href='".WEB_PUBLIC_PATH."/Css/admin_style.css' rel='stylesheet' type='text/css' />";
	    header("Content-type:text/html;charset=utf-8");
	    $show_dir="Public/Uploads";
		$root_dir=dirname($show_dir);
	    $path=base64_decode(urldecode($_GET["path"]));
        if($path=="" || $path==$root_dir) $path=$show_dir;
	    Vendor("LJW.Inc_File");
		$myfile=new Inc_File();
		$myfile->showfileanddir($path,__URL__);
		ob_end_flush();
	 }
	 public function delupload(){//删除上传图片
	    $pic=base64_decode(urldecode($_GET["pic"]));
		@chmod(dirname($pic),0777);
		@unlink($pic);

		$path=$_GET["path"];
		$this->redirect("showupload",array("path"=>$path));
	 }
	 public function downloadfile(){//下载文件
		 $path=base64_decode(urldecode($_GET["path"]));
		 if(empty($path)||!is_file($path))alert('文件不存在');
		 Vendor("LJW.Inc_File");
		 $myfile=new Inc_File;
		 $myfile->download($path);
	 }
	
	public function multiupload(){//多文件上传
	   $websetup=M("websetup");
	   $setup=$websetup->field("webname,weburl")->find();
	   $this->assign("setup",$setup);
	   $this->display();
	}
	public function flashupload(){
	   $websetup=M("websetup");
	   $setup=$websetup->field("webname,weburl")->find();
	   $this->assign("setup",$setup);
	   $this->display();
	}
	public function release(){//发布程序
	   //todo  主要是处理system里面的文件
	   //删除  system/Action  Common  Conf  LJW  Model   ORG  Public   Tpl .htaccess  config.php  delbom.php   index.php  sys_init.sql
	  
	  //删除 install.php
	}
	public function selectupload(){//选择上传的文件
	    header("Content-type:text/html;charset=utf-8");
	    $show_dir="Public/Uploads";
		$root_dir=dirname($show_dir);
	    $path=base64_decode(urldecode($_GET["path"]));
        if($path=="" || $path==$root_dir) $path=$show_dir;
	    Vendor("LJW.Inc_File");
		$myfile=new Inc_File();
		$thumbid=$_GET["thumbid"]?$_GET["thumbid"]:0;
		$myfile->selectupload($path,__ACTION__."/inputid/".$_GET["inputid"]."/thumbid/".$thumbid);
		
	}
	//@desc ajax 执行二级下拉
	//@return 返回json_encode值
	public function ajax2dropdown(){
		checkget();
		$cmodelname=$_GET["cmodelname"];
		$pmodelname=$_GET["pmodelname"];
		$c_field=$_GET["c_field"];
		$p_value=$_GET["p_value"];
		$field1=$_GET["field1"];
		$field2=$_GET["field2"];
		if($pmodelname=="sysclass"){
		  $syscolumn=M("syscolumn");
		  $col_id=$syscolumn->where("col_eng_name='$cmodelname'")->getField("id");
		  $map[$c_field]=array("in",typeid2child($p_value,$pmodelname,$col_id));	
		}else{
		  $map[$c_field]=$p_value;
		}
		$model=M($cmodelname);
		if(false!==array_search("sequence",$model->getDbFields(),true)){
		  $data=$model->where($map)->order("sequence desc")->field($field1.",".$field2)->findAll();	
		}else{
	      $data=$model->where($map)->field($field1.",".$field2)->findAll();
		}
		echo  json_encode($data);
	}
	protected $db =  NULL;
    public function initdb() {
        // 获取数据库对象实例
        $this->db   =  Db::getInstance();
    }
	public function db2(){//数据库操作2 参考thinkmyadmin
	   $this->display();
	}
	public function bakbytp(){//参考thinkmyadmin 数据库备份
	  checkget();
	  $this->initdb();
	  //是否压缩
	  $zip=$_GET["zip"];
	  //当前数据库
	  $curr_db=C("DB_NAME");
	  //获取当前数据库中的全部数据表
	  $tables =$this->db->getTables($curr_db);
	  $this->db->execute('USE '.$curr_db);
      // 组装导出SQL
      $sql  = "-- LJW SQL Dump\n-- contact to lijianwei_123@126.com\n\n";
      foreach($tables as $key=>$table) {
            $sql  .= "-- \n-- 表的结构 `$table`\n-- \n";
            $info  = $this->db->query("SHOW CREATE TABLE  $table");
			$sql.="DROP TABLE IF EXISTS $table;\n";
            $sql   .= $info[0]['Create Table'];
            $sql  .= ";\n-- \n-- 导出表中的数据 `$table`\n--\n";
            $result  =$this->db->query("SELECT * FROM $table ");
            foreach($result as $key=>$val) {
                foreach ($val as $k=>$field){
                     if(is_string($field)) {
                        $val[$k] = '\''.$this->db->escape_string($field).'\'';
                    }elseif(empty($field)){
                        $val[$k] =  'NULL';
                    }
                }
            	$sql  .= "REPLACE INTO `$table` VALUES (".implode(',',$val).");\n";
            }
        }
        $filename =$curr_db."bylijianwei"; 
        import("ORG.Net.Http");
        if(empty($zip)) {
            file_put_contents(TEMP_PATH.$filename.'.sql',trim($sql));
            Http::download (TEMP_PATH.$filename.'.sql');
        }else{
		  if(class_exists("ZipArchive")){
				
            $zip = new ZipArchive();
            if ($zip->open(TEMP_PATH.$filename.'.zip', ZIPARCHIVE::CREATE)!==TRUE) {
                exit("cannot open <$filename>\n");
            }
            $zip->addFromString($filename.'.sql',trim($sql));
            //$zip->addFile(TEMP_PATH.'thinkcms.sql',"ddd/test.sql");
            $zip->close();
            Http::download (TEMP_PATH.$filename.'.zip');
		  }else{
			  //todo 调用自己的压缩类别  有点问题
			  die("网站服务器不支持压缩文件，请使用数据库备份(无压缩)");
			   //file_put_contents(TEMP_PATH.$filename.'.sql',trim($sql));
			  // Vendor("LJW.zip");
			   //$zip = new PHPZip(); 
			   //$zip -> downloadZip(TEMP_PATH.$filename.'.sql',"压缩后的文件名.zip");
		  }
		}
	}
    public function rebakbytp() {//数据库还原  参考thinkmyadmin
	    set_time_limit(0);
		checkpost();
		$this->initdb();
        if(!empty($_FILES['sqlFile']['name'])) {
            // 判断文件后缀
            $pathinfo = pathinfo($_FILES['sqlFile']['name']);
            $ext  =   $pathinfo['extension'];
            if(!in_array($ext,array('sql','rar','gz','txt'))) {
                $this->error('文件格式不符合！');
            }
            // 导入SQL文件
            $sql   = file_get_contents($_FILES['sqlFile']['tmp_name']);
        }else{
            $this->error('选择要导入的文件');
        }
        $sql   = str_replace("\r\n", "\n", $sql);
        if($_POST['charset']!="utf-8")$sql   = auto_charset($sql,$_POST['charset'],'utf-8');
        unlink($_FILES['sqlFile']['tmp_name']);
        if(false === $this->patchExecute($sql)) {
            $this->error('导入错误！');
        }else{
            $this->success('导入完成！');
        }
    }
    // 批量执行SQL语句
    protected  function patchExecute($querySql) {
        if(is_string($querySql)) {
            $querySql   =  explode(";\n", trim($querySql)) ;
        }
        $ret = array();
        $num = 0;
        foreach($querySql as $query) {
            $queries = explode("\n", trim($query));
            foreach($queries as $query) {
                $ret[$num] .= $query[0] == '#' || $query[0].$query[1] == '--' ? '' : $query;
            }
            $num++;
        }
        $dbname=C("DB_NAME");
        $this->db->execute('USE '.$dbName);
        foreach($ret as $query) {
            if(!empty($query)) {
                $result   = $this->db->execute($query);
                if(false === $result) {
                    return false;
                }
            }
        }
        return $result;
    }
	public function del_html_cache(){//删除自定义缓存
	   set_time_limit(0);
	   $html_cache_dir=(substr(HTML_PATH,-1)=="/")?substr(HTML_PATH,0,-1):HTML_PATH;
	   $dir=dir($html_cache_dir);
	   while(false!==($file=$dir->read())){
		  if($file=="."||$file=="..")continue;
		  if(is_dir($html_cache_dir."/".$file)){
			  Vendor("LJW.Inc_File");
			  $myfile=new Inc_File;
			  $myfile->DeleteDir($html_cache_dir."/".$file);
		  }
	   }
	   $dir->close();
	   alert('删除成功');
	}
	public function relate_select(){//相关性 选择
	  checkget();
	  checkpost();
	  
	  $table=$_REQUEST["table"];
	  $select_field=$_REQUEST["select_field"];
	  $keyword_field=$_REQUEST["keyword_field"];
	  $field=$_REQUEST["field"];
	  
	  $this->assign("table",$table);
	  $this->assign("select_field",$select_field);
	  $this->assign("keyword_field",$keyword_field);
	  $this->assign("field",$field);
	  
	  if(empty($_REQUEST["action"])){
	     $this->display();
	  }elseif($_REQUEST["action"]=="ajax_search"){//ajax 搜索
	     $select_value=$_POST["select_value"];
		 $keyword_value=$_POST["keyword_value"];
	     $model=M($table);
		 //下拉搜索条件
		 if(!empty($select_value)){
			 $sysfield=M("sysfield");
			 $syscolumn=M("syscolumn");
			 $fill_value=$sysfield->where("col_eng_name='$table' and field_name='$field'")->getField("fill_value");
			 if(array_shift(explode("@",$fill_value))=="sysclass"){
				 $col_id=$syscolumn->where("col_eng_name='$table'")->getField("id");
				 $map[$select_field]=array("in",typeid2child($select_value,"sysclass","col_id=$col_id"));
			 }else{
				 $map[$select_field]=array("in",typeid2child($select_value,"sysclass","col_id=$col_id")); 
			 }
		 }
		 
		 if(!empty($keyword_value)){
			  $map[$keyword_field]=array("like","%$keyword_value%");
		 }
		 
		 $return_list = $model->where($map)->field("id,$keyword_field")->findAll();
		 foreach($return_list as $k=>$v){
			 $return_list[$k]['v']=$v['id'];
			 $return_list[$k]['k']=$v[$keyword_field]; 
		 }
		 echo json_encode($return_list);
	  }elseif($_REQUEST["action"]=="init_value"){//返回初始值
		 $init_value=$_GET["init_value"];
		 $table=$_GET["table"];
		 $keyword_field=$_GET["keyword_field"];
		 
		 $model=M($table);
		 $map["id"]=array("in",$init_value);
		 $return_list=$model->where($map)->field("id,$keyword_field")->findAll();
		 foreach($return_list as $k=>$v){
		     $return_list[$k]['v']=$v['id'];
			 $return_list[$k]['k']=$v[$keyword_field]; 
		 }
		 echo json_encode($return_list);
	  }
	}
	public function sysattr_ecshop(){//类ecshop商品属性
	   
	   $sysattr = M("sysattr");
	   
	   $col_id = $_GET["col_id"];
	   
	   $this->assign("col_id",$col_id);
	   
	   $field_value = $_GET["field_value"]; //规则  属性id [^ljw^] 属性值 [^jwl^] 属性id [^ljw^] 属性值
	   
	   if(!empty($field_value)){
		   $attr_list = explode("[^jwl^]",$field_value);
		   $attr_value = array();
		   foreach($attr_list as $k => $v){
			   $arr=explode("[^ljw^]",$v);
			   $attr_value[$arr[0]]=$arr[1];
		   }
		   
		   $first_attr_id = key($attr_value);
		   //查询出 使用的系统类型 id
		   $type_id = $sysattr->where("id = $first_attr_id")->getField("parid");
	   }
	   
	   //查询 所有系统 类型
	   
	   $type_list=$sysattr->where("parid = 0 and col_id = $col_id")->order("id")->findAll();
	   
	   $this->assign("type_list",$type_list);
	   
	   //查询 对应系统 类型 中 所有属性 
	   
	   if(empty($type_id)) $type_id = $type_list[0]['id'];
	   
	   $this->assign("type_id",$type_id);
	   
	   $attr_list = $sysattr->where("parid = $type_id")->order("sequence desc")->findAll();
	   
	   foreach($attr_list as $k => $v){
		   $attr_id = $v['id'];
		   if(isset($attr_value[$attr_id])) $attr_list[$k]['value']=$attr_value[$attr_id];
	   }
	   
	   $this->assign("attr_list",$attr_list);
	   
	   $this->display();
	}
	//ajax 获取 属性列表
	public function ajax_get_attr_list(){
	   $col_id = $_GET["col_id"];
	   
	   $type_id = $_GET["type_id"];
	   
	   $sysattr = M("sysattr");
	   
	   $attr_list = $sysattr->where("parid = $type_id and col_id = $col_id")->order("sequence desc")->findAll();
	   
	   echo json_encode($attr_list);

	}
    public function edit_admin_pwd(){//修改管理员密码
	   check_pression();
	   
	   $action = $_GET["action"];
	   if(empty($action)){
		  $this->display();  
	   }else if($action =="update"){
		   checkpost();
		   $admin_user = $_POST["admin"];
		   if($admin_user != $_SESSION["admin"]) alert('你没有权限修改{$admin}的密码');
		   
		   $admin = M("admin");
		   $admin->where("admin = '{$admin_user}'")->setField("password",$_POST["password"]);
		   
		   alert('修改成功');
	   }
	}
}
?>